#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
// ./tcp_server port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        cerr << "./tcp_server server_port" << endl;
        exit(-1);
    }
    string server_ip = "0.0.0.0";
    int16_t server_port = stoi(argv[1]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        cerr << "创建套接字失败" << endl;
    }
    cout << "创建套接字成功" << endl;

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    server.sin_port = htons(server_port);
    int bind_code = bind(sockfd, (struct sockaddr *)&server, sizeof(server));
    if (bind_code < 0)
    {
        cerr << "绑定失败" << endl;
    }
    cout << "绑定成功" << endl;

    int n = listen(sockfd, 2);
    if (n < 0)
    {
        cerr << "监听状态设置失败" << endl;
    }
    cout << "监听状态设置成功" << endl;

    while (true)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int listen_sock_fd = accept(sockfd, (struct sockaddr *)&client, &len);
        if (listen_sock_fd < 0)
        {
            cerr << "获取连接失败" << endl;
            continue;
        }
        cout << "获取了一个新的连接" << endl;
        while (true)
        {
            char request[1024];
            int read_nums = read(listen_sock_fd, &request, sizeof(request));
            if (read_nums > 0)
            {
                request[read_nums] = '\0';
                cout << "get a request from client # " << request << endl;

                int send_nums = write(listen_sock_fd, request, sizeof(request));
            }
            else if (read_nums == 0)
            {
                cout << "客户端退出" << endl;
                break;
            }
            else
            {
                cout << "读取数据失败" << endl;
            }
        }
        close(listen_sock_fd);
    }
}